const service = require('../service/user.service')

class UserController {
    async create(ctx, next) {
        // 获取用户请求的参数
        const user = ctx.request.body

        // 创建用户数据库
        const result = await service.create(user)

        // 返回数据
        ctx.body = result
    }

    async update(ctx, next) {
        const id = ctx.user.id
        const username = ctx.user.username
        let { filed, newValue } = ctx.request.body
        console.log('filed',filed,newValue)
        if(filed == 'avatar') {
            newValue = Buffer.from(newValue, 'base64')
            console.log('newvar',newValue)
        }
        try {
            const result = await service.updateUserInfo(filed, newValue, id, username)
            console.log(result[0].avatar)

            const imageBlob = result[0].avatar
            const imageBuffer = Buffer.from(imageBlob)
            const imageBase64 = imageBuffer.toString('base64')
            result[0].avatar = imageBase64
            ctx.body = result[0]
        } catch (error) {
            console.log('err',error)
        }
        
    }

    async updateUserInfo(ctx, next) {
        // console.logre
        console.log('2')
console.log('ctx.request.body',ctx.request.body)
        const { id, user } = ctx.request.body;
        console.log('id, user',id, user)
        const columns = Object.keys(user); // 获取用户提供的字段
        let sql = `UPDATE users SET `;
        let values = [];
        // 根据用户提供的字段动态构建 SQL 语句
        columns.forEach((column, index) => {
        if(column == 'desc') {
            column = '`desc`'
        }
        sql += `${column} = "${user[column]}"`;
        values.push(user[column]);
        if (index !== columns.length - 1) {
            sql += ', ';
        }
        });
        sql += ` WHERE id = ${id}`;
        console.log('sql',sql)
        const result = await service.updateInfo(id, columns,sql)
        ctx.body = result
    }

    async getUserDetailById(ctx, next) {
        console.log('1')
        const { userId } = ctx.params
        console.log('useid',userId)

        const result = await service.getUserDetail(userId)
        const imageBlob = result[0].avatar
        const imageBuffer = Buffer.from(imageBlob)
        const imageBase64 = imageBuffer.toString('base64')
        result[0].avatar = imageBase64
        ctx.body = result[0]
    }
}

module.exports = new UserController()
